﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PetaPoco;
using BrnMall.Core;

namespace BrnMall.Manager.Manager.Order
{
    public static class OrderManager
    {
        public static void UpdatePrepayId(int oid, string prepayId)
        {
            using (var db = new QDMallDatabase())
            {
                db.Execute("update bma_orders set prepay_id=@0 where oid=@1", prepayId, oid);
            }
        }

        public static string GetPrepayId(int oid)
        {
            using (var db = new QDMallDatabase())
            {
                return db.ExecuteScalar<string>("select prepay_id from bma_orders where oid=@0", oid);
            }
        }

        /// <summary>
        ///  获取订单的使用的余额支付
        /// </summary>
        /// <param name="oid"></param>
        /// <returns></returns>
        public static decimal GetPayCash(int oid)
        {
            object obj = null;
            using (var db = new QDMallDatabase())
            {
                obj = db.ExecuteScalar<object>("select paycash from bma_orders where oid=@0", oid);
            }
            if (obj == null || obj == DBNull.Value)
                return 0;
            return Convert.ToDecimal(obj);
        }

        /// <summary>
        /// 更新订单的余额、微信支付金额、订单状态
        /// </summary>
        /// <param name="oid"></param>
        /// <param name="payCash"></param>
        /// <param name="surplusMoney"></param>
        /// <param name="orderState"></param>
        public static int UpdatePayCash(int oid, decimal payCash, decimal surplusMoney, int orderState)
        {
            using (var db = new QDMallDatabase())
            {
                return db.Execute("update bma_orders set payCash=@0,surplusMoney=@1,orderState=@2 where oid=@3", payCash, surplusMoney, orderState, oid);
            }
        }


        /// <summary>
        /// 订单金额汇总
        /// </summary>
        /// <param name="storeId"></param>
        /// <param name="uid"></param>
        /// <param name="nickName"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        public static Domain.User.TotalMoneyModel GetTotalMoney(int storeId, int uid, string nickName, string startTime, string endTime)
        {
            Domain.User.TotalMoneyModel model = null;

            var sql = new StringBuilder();
            sql.Append("select SUM(orderamount) as orderamount,SUM(surplusmoney) as surplusmoney,SUM(paycreditmoney) as paycreditmoney,sum(couponmoney) as couponmoney,SUM(fullcut) as fullcut from bma_orders where orderstate >= 80 and orderstate < 140 and paymode = 1");

            sql.AppendFormat(" and storeId={0}", storeId);
            if (uid > 0)
                sql.AppendFormat(" and uid={0}", uid);

            //昵称查询
            if (!string.IsNullOrEmpty(nickName))
            {
                var uids = User.UsersManager.GetIdsByNickNameToString(nickName, 20);
                if (uids.IndexOf(",") > -1)
                    sql.AppendFormat(" and uid in({0})", uids);
                else
                    sql.AppendFormat(" and uid={0}", uids);
            }

            if (!string.IsNullOrEmpty(startTime))
                sql.AppendFormat(" and addtime>='{0}'", startTime);

            if (!string.IsNullOrEmpty(endTime))
                sql.AppendFormat(" and addtime<'{0}'", Convert.ToDateTime(endTime).AddDays(1));

            using (var db = new QDMallDatabase())
            {
                model = db.SingleOrDefault<Domain.User.TotalMoneyModel>(sql.ToString());
            }
            return model;
        }

        public static IList<int> GetOrderPidsBySendTime(DateTime sendTime)
        {
            using (var db = new QDMallDatabase())
            {
                return db.Fetch<int>("select oid from  [bma_orders] WHERE [orderstate]=100 AND [shiptime]<@0", sendTime);
            }
        }

        /// <summary>
        /// 获得订单列表搜索条件范围
        /// </summary>
        /// <param name="storeId">店铺id</param>
        /// <param name="osn">订单编号</param>
        /// <param name="uid">用户id</param>
        /// <param name="consignee">收货人</param>
        /// <param name="startOrderState">订单开始</param>
        /// <param name="endOrderState">订单结束</param>
        /// <param name="sid">桌号</param>
        /// <returns></returns>
        public static string GetOrderListCondition(int storeId, string osn, int uid, string consignee, int startOrderState, int endOrderState, string sid)
        {
            var condition = new StringBuilder();

            if (storeId > 0)
                condition.AppendFormat(" AND [storeid] = {0} ", storeId);
            if (!string.IsNullOrWhiteSpace(osn) && SecureHelper.IsSafeSqlString(osn))
                condition.AppendFormat(" AND [osn] like '{0}%' ", osn);
            if (uid > 0)
                condition.AppendFormat(" AND [uid] = {0} ", uid);
            if (!string.IsNullOrWhiteSpace(consignee) && SecureHelper.IsSafeSqlString(consignee))
                condition.AppendFormat(" AND [consignee] like '{0}%' ", consignee);
            if (startOrderState > 0 && endOrderState < 0)
                condition.AppendFormat(" AND [orderstate] >= {0} ", startOrderState);
            if (startOrderState < 0 && endOrderState > 0)
                condition.AppendFormat(" AND [orderstate] <= {0} ", endOrderState);
            if (startOrderState > 0 && endOrderState > 0)
                condition.AppendFormat(" AND [orderstate] BETWEEN {0} AND {1}", startOrderState, endOrderState);
            if (!string.IsNullOrEmpty(sid))
                condition.AppendFormat(" AND sid='{0}'", sid);
            return condition.Length > 0 ? condition.Remove(0, 4).ToString() : "";
        }

    }
}